from django import forms
from django.core.exceptions import ValidationError

from web.forms.bootstrap import BootStrapForm
from web.forms.widgets import ColorRadioSelect
from web import models


class ProjectModelForm(BootStrapForm, forms.ModelForm):
    bootstrap_class_exclude = ['color']#实现color免除BootStrapForm 以保证其的正常排版

    # desc = forms.CharField(widget=forms.Textarea(attrs={'xx': 123}))
    class Meta:
        model = models.Project
        fields = ['name', 'color', 'desc']
        # fields = "__all__"
        widgets = {
            'desc': forms.Textarea,
            # 'color':forms.Select#默认是forms.Select 即是下拉框的样子
            # 'color':forms.RadioSelect,#系统自带的插件
            'color': ColorRadioSelect(attrs={'class': 'color-radio'})
            #自己写的插件#其中attr={xxx}是父类BootStrapForm中定义的设置元素属性的方法啊

                # class BootStrapForm(object):
                #     bootstrap_class_exclude = []  # exclude 样式
                #
                #     def __init__(self, *args, **kwargs):
                #         super().__init__(*args, **kwargs)
                #         for name, field in self.fields.items():
                #             if name in self.bootstrap_class_exclude:
                #                 continue
                #             old_class = field.widget.attrs.get('class', "")
                #             field.widget.attrs['class'] = '{} form-control'.format(old_class)
                #             field.widget.attrs['placeholder'] = '请输入%s' % (field.label,)

        }

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_name(self):
        """ 项目校验 """
        name = self.cleaned_data['name']
        # 1. 当前用户是否已创建过此项目(项目名是否已存在)？
        exists = models.Project.objects.filter(name=name, creator=self.request.tracer.user).exists()
        if exists:
            raise ValidationError('项目名已存在')

        # 2. 当前用户是否还有额度进行创建项目？
        # 最多创建N个项目
        # self.request.tracer.price_policy.project_num

        # 现在已创建多少项目？
        count = models.Project.objects.filter(creator=self.request.tracer.user).count()

        if count >= self.request.tracer.price_policy.project_num:
            raise ValidationError('项目个数超限，请购买套餐')

        return name
